package com.example.scanner.zxing.qrcode;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 二维码生成与识别工具类
 *
 * @author zwg
 * @date 2025/8/12 22:45
 */
@Slf4j
public class QRCodeUtil {

    // 二维码颜色
    private static final int QR_COLOR = 0xFF000000; // 默认黑色
    // 二维码背景色
    private static final int BG_WHITE = 0xFFFFFFFF; // 白色

    // 二维码图片宽度
    private static final int WIDTH = 300;
    // 二维码图片高度
    private static final int HEIGHT = 300;
    // 二维码图片格式
    private static final String FORMAT = "png";

    private static final String CHARACTER_SET = "UTF-8";

    /**
     * 生成二维码图片
     * @param content 二维码内容
     * @param filePath 保存路径
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static void generateQRCode(String content, String filePath) throws WriterException, IOException {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 编码格式
        hints.put(EncodeHintType.CHARACTER_SET, CHARACTER_SET);
        // 纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 边距
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码矩阵
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

        // 保存二维码图片
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);

        log.info("二维码生成成功，保存路径：{}", filePath);
    }

    /**
     * 生成二维码图片
     * @param content 二维码内容
     * @return String 二维码图片base64字符串
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static String generateQRCode(String content) throws WriterException, IOException {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        // 编码格式
        hints.put(EncodeHintType.CHARACTER_SET, CHARACTER_SET);
        // 纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 边距
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码矩阵
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

        // 保存二维码图片
        //Path path = FileSystems.getDefault().getPath(filePath);
        //MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path);
        BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);

        log.info("二维码生成成功，保存成base64字符串");
        return bufferedImageToBase64(image,FORMAT);
    }

    /**
     * 将BufferedImage转换为Base64字符串
     * @param image 要转换的BufferedImage对象
     * @param formatName 图像格式（如"png"、"jpg"、"jpeg"）
     * @return Base64编码字符串，包含数据协议头（如data:image/png;base64,）
     * @throws IOException 图像处理异常
     */
    public static String bufferedImageToBase64(BufferedImage image, String formatName) throws IOException {
        if (image == null) {
            throw new IllegalArgumentException(" BufferedImage cannot be null");
        }

        // 创建字节输出流
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            // 将图像写入字节流
            ImageIO.write(image, formatName, outputStream);

            // 转换字节数组为Base64字符串
            byte[] imageBytes = outputStream.toByteArray();
            String base64Encoded = Base64.getEncoder().encodeToString(imageBytes);

            // 拼接数据协议头，方便前端直接使用
            return "data:image/" + formatName + ";base64," + base64Encoded;
        }
    }

    /**
     * 生成带logo的二维码图片
     * @param content 二维码内容
     * @param filePath 保存路径
     * @param logoPath logo图片路径
     * @throws WriterException 写入异常
     * @throws IOException IO异常
     */
    public static void generateQRCodeWithLogo(String content, String logoPath, String filePath)
            throws WriterException, IOException {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, CHARACTER_SET);
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高纠错级别，适合添加logo
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码矩阵
        BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);

        // 转换为BufferedImage
        BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

        // 读取logo图片
        BufferedImage logoImage = ImageIO.read(new File(logoPath));

        // 计算logo的尺寸，一般为二维码的1/5
        int logoWidth = logoImage.getWidth() > qrImage.getWidth() / 5 ? qrImage.getWidth() / 5 : logoImage.getWidth();
        int logoHeight = logoImage.getHeight() > qrImage.getHeight() / 5 ? qrImage.getHeight() / 5 : logoImage.getHeight();

        // 计算logo的位置，居中显示
        int x = (qrImage.getWidth() - logoWidth) / 2;
        int y = (qrImage.getHeight() - logoHeight) / 2;

        // 将logo绘制到二维码上
        Graphics2D graphics = qrImage.createGraphics();
        graphics.drawImage(logoImage, x, y, logoWidth, logoHeight, null);

        // 给logo添加边框
        graphics.setStroke(new BasicStroke(1));
        graphics.setColor(Color.WHITE);
        graphics.drawRect(x, y, logoWidth, logoHeight);

        graphics.dispose();
        logoImage.flush();
        qrImage.flush();

        // 保存带logo的二维码图片
        ImageIO.write(qrImage, FORMAT, new File(filePath));

        log.info("带logo的二维码生成成功，保存路径：{}",filePath);
    }


    /**
     * 生成带Logo的二维码图片, logo图片保存原图片颜色
     *
     * @param content 二维码内容
     * @param width 二维码宽度
     * @param height 二维码高度
     * @param logoPath Logo图片路径
     * @param outputPath 生成的二维码保存路径
     * @throws Exception 可能抛出的异常
     */
    public static void generateQRCodeWithColorLogo(String content, int width, int height,
                                              String logoPath, String outputPath) throws Exception {
        // 设置二维码参数
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 高容错级别，便于添加Logo
        hints.put(EncodeHintType.MARGIN, 1);

        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
                BarcodeFormat.QR_CODE, width, height, hints);

        // 生成二维码图片
        BufferedImage qrImage = toBufferedImage(bitMatrix);

        // 添加Logo
        if (logoPath != null && !logoPath.isEmpty()) {
            qrImage = addLogo(qrImage, logoPath);
        }

        // 保存二维码图片
        File outputFile = new File(outputPath);
        ImageIO.write(qrImage, "png", outputFile);
    }

    /**
     * 将BitMatrix转换为BufferedImage
     */
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? QR_COLOR : BG_WHITE);
            }
        }

        return image;
    }

    /**
     * 给二维码添加Logo
     */
    private static BufferedImage addLogo(BufferedImage qrImage, String logoPath) throws IOException {
        // 读取Logo图片
        File logoFile = new File(logoPath);
        if (!logoFile.exists()) {
            throw new IOException("Logo文件不存在: " + logoPath);
        }

        BufferedImage logoImage = ImageIO.read(logoFile);

        // 获取二维码和Logo的宽度和高度
        int qrWidth = qrImage.getWidth();
        int qrHeight = qrImage.getHeight();
        int logoWidth = logoImage.getWidth();
        int logoHeight = logoImage.getHeight();

        // 设置Logo大小为二维码的1/5
        if (logoWidth > qrWidth / 5 || logoHeight > qrHeight / 5) {
            logoWidth = qrWidth / 5;
            logoHeight = qrHeight / 5;

            // 调整Logo大小
            Image tempImage = logoImage.getScaledInstance(logoWidth, logoHeight, Image.SCALE_SMOOTH);
            BufferedImage resizedLogo = new BufferedImage(logoWidth, logoHeight, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = resizedLogo.createGraphics();
            g.drawImage(tempImage, 0, 0, null);
            g.dispose();
            logoImage = resizedLogo;
        }

        // 计算Logo放置的位置（居中）
        int x = (qrWidth - logoWidth) / 2;
        int y = (qrHeight - logoHeight) / 2;

        // 在二维码上绘制Logo，保持原有颜色
        Graphics2D g = qrImage.createGraphics();
        // 如果Logo有透明背景，这里的绘制方式会保留透明度
        g.drawImage(logoImage, x, y, logoWidth, logoHeight, null);

        // 可选：给Logo添加边框
        // g.setStroke(new BasicStroke(2));
        // g.setColor(Color.WHITE);
        // g.drawRect(x, y, logoWidth, logoHeight);

        g.dispose();

        return qrImage;
    }



    /**
     * 识别二维码图片内容
     * @param filePath 二维码图片路径
     * @return 二维码内容
     * @throws IOException IO异常
     * @throws NotFoundException 未找到二维码异常
     */
    public static String decodeQRCode(String filePath) throws IOException, NotFoundException {
        // 读取二维码图片
        File file = new File(filePath);
        BufferedImage image = ImageIO.read(file);

        // 解析二维码
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

        // 设置解码参数
        Map<DecodeHintType, Object> hints = new HashMap<>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARACTER_SET);

        // 解码
        Result result = new MultiFormatReader().decode(bitmap, hints);

        return result.getText();
    }
}
